#!/bin/bash
# chkconfig: 2345 21 60
#create by 51yuki
#This script is the rsync service script
. /etc/rc.d/init.d/functions

function startrsync(){
	echo "rsync is startting"
	/usr/bin/rsync --daemon --config=/etc/rsyncd.conf
	sleep 2
	Rsyncport=$(netstat -nultp|grep 873|wc -l)
	if [ ${Rsyncport} -eq 2 ];then
		action "rsyncd start" /bin/true
	else
		action "rsyncd start" /bin/false
	fi
}
function stoprsync(){
	echo "rsync is stopping"
	Rsyncport=`netstat -nultp|grep 873|wc -l`
        if [ $Rsyncport -eq 2 ];then	
	    killall rsync &>/dev/null
	    rm -rf /var/run/rsyncd.pid
	    sleep 2
	fi
	Rsyncport=`netstat -nultp|grep 873|wc -l`
        if [ ${Rsyncport} -ne 2 ];then
                action "rsyncd stop" /bin/true
        else
                action "rsyncd stop" /bin/false
        fi
}
function statusrsync(){
	echo "rsync is restarting"
	Rsyncport=$(netstat -nultp|grep 873|wc -l)
        if [ ${Rsyncport} -eq 2 ];then
        	echo  "rsync is running"
        else
        	echo "rsync is stoped"
        fi
}
function restartrsync(){
	Rsyncport=$(netstat -nultp|grep 873|wc -l)
        if [ ${Rsyncport} -eq 0 ];then
		/usr/bin/rsync --daemon --config=/etc/rsyncd.conf
	sleep 2
	if [ ${Rsyncport} -eq 2 ];then
		action "rsync restart" /bin/true
	else
		action "rsync restart" /bin/false
	fi
	else
		killall rsync &>/dev/null
		rm -rf /var/run/rsyncd.pid
		sleep 2
		/usr/bin/rsync --daemon --config=/etc/rsyncd.conf
		Rsyncport=`netstat -lntup|grep 873|wc -l`
        	if [ $Rsyncport -eq 2 ];then
      			action "rsync restart"   /bin/true
        	else
        		action "rsync restart"   /bin/false
        	fi	
	fi
}
case $1 in
start)
	startrsync
	;;
stop)
	stoprsync
	;;
restart)
	restartrsync
	;;
status)
	statusrsync
	;;
*)
	echo $"Usage: $0 {start|stop|status|restart}"
	
esac


